<?php
	/**
	 * Created by PhpStorm.
	 * User: mybook-lhp
	 * Date: 18/3/23
	 * Time: 下午9:58
	 */


	class RsaCrypt
	{
		const PRIVATE_KEY_FILE_PATH = './cert/apiclient_key.pem';
		const PUBLIC_KEY_FILE_PATH  = './cert/apiclient_cert.pem';

		public static function encode($orignData)
		{
			//密钥文件的路径
			$privateKeyFilePath = self::PRIVATE_KEY_FILE_PATH;
			extension_loaded('openssl') or die('php需要openssl扩展支持');
			(file_exists($privateKeyFilePath)) or die('密钥的文件路径不正确');
			//生成Resource类型的密钥，如果密钥文件内容被破坏，openssl_pkey_get_private函数返回false
			$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyFilePath));

			($privateKey) or die('密钥不可用');
			//加密以后的数据，用于在网路上传输
			$encryptData = '';
			///////////////////////////////用私钥加密////////////////////////
			if (openssl_private_encrypt($orignData, $encryptData, $privateKey)) {
				return $encryptData;
			} else {
				die('加密失败');
			}
		}

		public static function decode($encryptData)
		{
			//公钥文件的路径
			$publicKeyFilePath = self::PUBLIC_KEY_FILE_PATH;
			extension_loaded('openssl') or die('php需要openssl扩展支持');
			(file_exists($publicKeyFilePath)) or die('公钥的文件路径不正确');
			//生成Resource类型的公钥，如果公钥文件内容被破坏，openssl_pkey_get_public函数返回false
			$publicKey = openssl_pkey_get_public(file_get_contents($publicKeyFilePath));
			($publicKey) or die('公钥不可用');
			//解密以后的数据
			$decryptData = '';
		}


	}

	$dn = array(

		"countryName" => 'cn', //所在国家名称

		"stateOrProvinceName" => 'Cichuan', //所在省份名称

		"localityName" => 'ChengduCity', //所在城市名称

		"organizationName" => 'DragonPaul',   //注册人姓名

		"organizationalUnitName" => 'Dragon', //组织名称

		"commonName" => 'Paul', //公共名称

		"emailAddress" => 'dragon_lhp@163.com' //邮箱

	);

	$privkeypass = 'Dragonlhp123'; //私钥密码

	$numberofdays = 365;     //有效时长

	$cerpath = "./rsa/test.cer"; //生成证书路径

	$pfxpath = "./rsa/test.pfx"; //密钥文件路径


//	//生成证书
//
//	$privkey = openssl_pkey_new();
//
//	$csr = openssl_csr_new($dn, $privkey);
//
//	$sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
//
//	openssl_x509_export_to_file($sscert, $cerpath); //导出证书到文件
//
//	openssl_pkcs12_export_to_file($sscert, $pfxpath, $privkey, $privkeypass); //生成密钥文件

	$m = RsaCrypt::encode([1, 2, 3, 4, 5, 6, 76]);

	var_dump($m);

	var_dump(RsaCrypt::decode($m));


